`
https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/
`

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */

/**
 * Encodes a tree to a single string.
 *
 * @param {TreeNode} root
 * @return {string}
 */
var serialize = function (root) {
  const res = []

  // 序列化函数
  function _serialize(node) {
    // 用 '#' 表示空指针
    if (node === null) {
      return res.push('#')
    }

    // 前序遍历序列
    res.push(`${node.val}`)

    _serialize(node.left)
    _serialize(node.right)
  }

  _serialize(root)

  return res.join(',')
};

/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function (data) {
  // 获取存储每个结点值的列表
  const nodes = data.split(',')

  function _deserialize(nodes) {
    if (nodes.length === 0) {
      return null
    }

    const val = nodes.shift()
    if (val === '#') return null

    // 前序逆序列化
    const node = new TreeNode(+val)

    node.left = _deserialize(nodes)
    node.right = _deserialize(nodes)

    return node
  }

  return _deserialize(nodes)
};

/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/